# coding=utf-8

import sys
import xbmc
import xbmcgui
import xbmcplugin
import xbmcaddon
import subprocess
import urllib
import re
from time import sleep

class Recorder:
	_pluginId = 0
	_pluginName = ""
	_addon = None

	def __init__(self, pluginId, pluginName):
		self._pluginId = pluginId
		self._pluginName = pluginName
		self._addon = xbmcaddon.Addon(self._pluginName)
		print "Plugin ID: " + str(self._pluginId)
		print "Plugin Name: " + self._pluginName

	def send(self, listing):
		for item in listing:
			station = item[0]
			playbackURL = item[1]
			listItem = xbmcgui.ListItem(station)
			listItem.setProperty("mimetype", "audio/mpeg")
			recordParams = {"mode" : "record", "url" : playbackURL.encode("utf-8")}
			editParams = {"mode" : "edit", "station" : station.encode("utf-8"), "url" : playbackURL.encode("utf-8")}
			addParams = {"mode" : "add"}
			removeParams = {"mode" : "remove", "station" : station.encode("utf-8")}
			listItem.addContextMenuItems([
				(self._addon.getLocalizedString(3000),
					"XBMC.RunPlugin(plugin://%s?%s)" % (self._pluginName, urllib.urlencode(recordParams))),
				(self._addon.getLocalizedString(3010),
					"XBMC.RunPlugin(plugin://%s?%s)" % (self._pluginName, urllib.urlencode(editParams))),
				(self._addon.getLocalizedString(3020),
					"XBMC.RunPlugin(plugin://%s?%s)" % (self._pluginName, urllib.urlencode(addParams))),
				(self._addon.getLocalizedString(3030),
					"XBMC.RunPlugin(plugin://%s?%s)" % (self._pluginName, urllib.urlencode(removeParams)))
			])
			xbmcplugin.addDirectoryItem(self._pluginId, playbackURL, listItem)

	def record(self, url):
		duration = xbmcgui.Dialog().numeric(0, self._addon.getLocalizedString(2000))
		if duration != "":
			if xbmcgui.Dialog().yesno(self._addon.getLocalizedString(2001), self._addon.getLocalizedString(2002)):
				self._recordNow(url, duration)
			else:
				startDate = xbmcgui.Dialog().numeric(1, self._addon.getLocalizedString(2003))
				startTime = xbmcgui.Dialog().numeric(2, self._addon.getLocalizedString(2004))
				self._recordLater(url, duration, startDate, startTime)

	def _recordNow(self, url, duration):
		dir = xbmcplugin.getSetting(self._pluginId, "storage_location")
		proc = subprocess.Popen(["streamripper", url, "-l", duration, "-a", "-A", "-d", "%s" % (dir)])
		pDialog = xbmcgui.DialogProgress()
		pDialog.create(self._addon.getLocalizedString(3040), url)
		percentage = 100 / int(duration)
		for i in range(0, 100, percentage):
			pDialog.update(i, url)
			sleep(1)
		pDialog.close()

	def _recordLater(self, url, duration, dateString, timeString):
		dateString = self._formatDate(dateString)
		streamripper = "streamripper " + url + " -l " + duration + " -a -A -d /home/tobias/versuch"
		proc = subprocess.Popen(["at", "%s %s" % (timeString, dateString)], stdin=subprocess.PIPE, stderr=subprocess.PIPE)
		output = proc.communicate(streamripper)[1]
		if proc.returncode == 0:
			self._showMessage(self._addon.getLocalizedString(3050), self._addon.getLocalizedString(3060), "DefaultIconInfo.png")
		else:
			self._showMessage(self._addon.getLocalizedString(3051), output, "DefaultIconError.png")
 
	def editURL(self, url, station):
		return self._getKeyboardInput(url, self._addon.getLocalizedString(2010) + '"' + station + '"')

	def editStationName(self, station):
		return self._getKeyboardInput(station, self._addon.getLocalizedString(2011) + '"' + station + '"')

	def addStation(self):
		return self._getKeyboardInput("", self._addon.getLocalizedString(2020))

	def _getKeyboardInput(self, default, header):
		input = default
		kb = xbmc.Keyboard(default, header, False)
		kb.doModal()
		if kb.isConfirmed():
			input = kb.getText()

		return input.decode("utf-8")

	def _formatDate(self, dateString):
		atDate = re.sub("/\s*", ".", dateString)
		return atDate

	def _showMessage(self, header, msg, icon):
		xbmc.executebuiltin(("XBMC.Notification(%s, %s, 5000, %s)" % (header, msg, icon)).encode("utf-8"))
